//
//  FQIDCardAuthViewController.swift
//  SwiftProject
//
//  Created by 董駸 on 2022/8/22.
//

import UIKit
import AttributedString

class FQIDCardAuthViewController: BaseViewController {
    let manualBtn = QMUIButton()
    let tipView = FQCerificationTipView(0)
    
    let isValidFace = BehaviorRelay(value: false)
    let isValidBack = BehaviorRelay(value: false)
    let buttonIsSelected = BehaviorRelay(value: true)
    let whiteV = UIView()

    lazy var cInputView : FQCerificationInputView = {
        let cInputView = FQCerificationInputView(0)
        view.addSubview(cInputView)
        
        cInputView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(cInputView.qmui_height)
            make.top.equalTo(whiteV.snp.bottom).offset(10)
        }
        
        return cInputView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationBarType = .light
    }
    
    override func initSubviews() {
        super.initSubviews()
        
        let titleLb = QMUILabel(font: .mSFont(21), textColor: .color51)
        view.addSubview(titleLb)
        
        titleLb.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.top.equalTo(NavigationContentTop + 32)
        }
        
        let titleStr : ASAttributedString = """
            上传本人身份证 \("激活额度", .foreground(.qmui_color(withHexString: "ec9756")!))
            """
        titleLb.attributed.text = titleStr
        
        let subTitleLb = QMUILabel(font: .rSFont(13), textColor: .color149)
        subTitleLb.text = "用于身份实名核验、反洗钱及额度评估，资料将被加密保护"
        subTitleLb.numberOfLines = 0
        view.addSubview(subTitleLb)
        
        subTitleLb.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.top.equalTo(titleLb.snp.bottom).offset(10)
            make.right.equalTo(-20)
        }
        
        safeAreaBottomView.backgroundColor = .white
        
        let bottomView = FQAuthBottonView()
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(90)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
        }
        
        bottomView.toggleBlock = { [unowned self] isSelected in
            self.buttonIsSelected.accept(isSelected)
        }
        
        bottomView.buttonBlock = { [unowned self] in
            let aesName = WMEncryptTool.manager.aesEncrypt(self.cInputView.nameTF.text!)
            let aesIdCard = WMEncryptTool.manager.aesEncrypt(self.cInputView.idTF.text!)
            NetworkManager.manager.request(targetType: .genRealPersonVerificationToken(name: aesName, idCard: aesIdCard, metaInfo: AliyunIdentityManager.getMetaInfo().toJSONString), responseModelType: NetworkBaseModel<FQIDCardModel>.self) { responseModel in
                if responseModel.code != .successCode {
                    QMUITips.showError(responseModel.msg)
                    return
                }
                let model = YHBaseConfiguration.shared.configModel!
                let userModel = BaseUserModel.unarchiver()!
                if model.face && !userModel.isFace {
                    let vc = FQFaceCerificationViewController()
                    vc.idCardAes = aesIdCard
                    vc.nameAes = aesName
                    vc.verificationToken = responseModel.data!.verificationToken
                    self.navigationController?.qmui_pushViewController(vc, animated: true)
                } else {
                    if model.relationship && !userModel.isAccomplishRelationship {
                        let vc = FQFillInfoViewController(.kinsfolk)
                        vc.idCardAes = aesIdCard
                        vc.nameAes = aesName
                        self.navigationController?.qmui_pushViewController(vc, animated: true)
                    } else {
                        let vc = FQFillInfoViewController(.baseInfo)
                        vc.idCardAes = aesIdCard
                        vc.nameAes = aesName
                        self.navigationController?.qmui_pushViewController(vc, animated: true)
                    }
                }
            }
        }
        
        whiteV.backgroundColor = .white
        view.addSubview(whiteV)
        
        whiteV.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(subTitleLb.snp.bottom).offset(32)
            make.height.equalTo(134~)
        }
        
        let image1 = FQUpdateImageView(.face)
        image1.addTarget(self, action: #selector(updateImage(_:)), for: .touchUpInside)
        whiteV.addSubview(image1)
        
        image1.snp.makeConstraints { make in
            make.left.equalTo(20~)
            make.centerY.equalToSuperview()
            make.size.equalTo(CGSize(width: 152, height: 95)~)
        }
        
        let image2 = FQUpdateImageView(.back)
        image2.addTarget(self, action: #selector(updateImage(_:)), for: .touchUpInside)
        whiteV.addSubview(image2)
        
        image2.snp.makeConstraints { make in
            make.right.equalTo(-20~)
            make.centerY.size.equalTo(image1)
        }
        
        manualBtn.backgroundColor = .white
        manualBtn.qmui_borderColor = .color238
        manualBtn.qmui_borderWidth = 0.5
        manualBtn.qmui_borderPosition = .top
        manualBtn.addTarget(self, action: #selector(toManual), for: .touchUpInside)
        view.addSubview(manualBtn)
        
        manualBtn.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(whiteV.snp.bottom)
            make.height.equalTo(50)
        }
        
        let tipBtn = QMUIButton()
        tipBtn.setTitle("身份证不在身边？手动填入身份信息", for: .normal)
        tipBtn.setTitleColor(.color51, for: .normal)
        tipBtn.titleLabel?.font = .rSFont(13)
        tipBtn.setImage(UIImage(named: "icon_tishi"), for: .normal)
        tipBtn.imagePosition = .left
        tipBtn.spacingBetweenImageAndTitle = 8
        tipBtn.isUserInteractionEnabled = false
        manualBtn.addSubview(tipBtn)
        
        tipBtn.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.centerY.equalToSuperview()
        }
        
        let arrow = ArrowButton(arrowSize: CGSize(width: 6, height: 12), arrowColor: .color153, arrowDirection: .right, lineWidth: 1)
        manualBtn.addSubview(arrow)
        
        arrow.snp.makeConstraints { make in
            make.right.equalTo(-20)
            make.centerY.equalToSuperview()
        }
        
        view.addSubview(tipView)
        tipView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(manualBtn.snp.bottom).offset(15)
            make.height.equalTo(tipView.qmui_height)
        }
        
        isValidFace.subscribe (onNext: { [unowned self] isVaild in
            self.tipView.isHidden = isVaild
            self.manualBtn.isHidden = isVaild
            self.cInputView.isHidden = !isVaild
        }).disposed(by: rx.disposeBag)

        Driver.combineLatest(isValidFace.asDriver(), isValidBack.asDriver(), buttonIsSelected.asDriver(), resultSelector: {(faceIsValid, backIsValid, buttonIsSelected) -> Bool in
            (faceIsValid && backIsValid && buttonIsSelected)
        }).distinctUntilChanged().drive(bottomView.completionBtn.rx.buttonIsEnable).disposed(by: rx.disposeBag)
    }
    
    @objc func updateImage(_ button : FQUpdateImageView) {
        let actions: [QMUIAlertController.AlertAction] = [
            .action(title: "拍照"),
            .action(title: "从手机相册选择"),
            .action(title: "取消", style : .cancel)
        ]

        QMUIAlertController.present(title: nil, message: nil, style: .actionSheet, actions: actions).subscribe(onNext: { buttonIndex in
            PromiseManager.shared.getCameraPermissionsCompletion { [unowned self] isOn in
                UIImagePickerController.rx.createWithParent(self) { picker in
                    picker.sourceType = buttonIndex == 0 ? .camera : .photoLibrary
                    picker.allowsEditing = true
                }.flatMap { $0.rx.didFinishPickingMediaWithInfo }.take(1).subscribe(onNext: { dict in
                    let image = dict[UIImagePickerController.InfoKey.editedImage] as! UIImage
                    
                    AliyunOSSUpdateManager.manager.ossClient.updateImagesWith(imageArray: [image.jpegData(compressionQuality: 0.7)!], inView: self.view) { urlArray in
                        NetworkManager.manager.request(targetType: .recognizeIdcard(url: urlArray[0]), responseModelType: NetworkBaseModel<FQIDCardModel>.self) { responseModel in
                            if responseModel.code != .successCode {
                                self.showFail(button.updateType)
                                return
                            }
                            if button.updateType == .face {
                                self.isValidFace.accept(true)
                                self.cInputView.idTF.text = WMEncryptTool.manager.aesDecode(responseModel.data!.idNumber)
                                self.cInputView.nameTF.text = WMEncryptTool.manager.aesDecode(responseModel.data!.userName)
                            } else {
                                self.isValidBack.accept(true)
                            }
                            button.setBackgroundImage(image, for: .normal)
                            button.status = true
                        }
                    } failure: { error in
                        QMUITips.showError(error)
                    }
                }).disposed(by: disposeBag)
            }
        }).disposed(by: disposeBag)
    }
    
    func showFail(_ type : FQUpdateType) {
        let v = FQFaceCerificationFailView(type)
        modalViewControllerForAddSubview.contentView = v
        modalViewControllerForAddSubview.layoutBlock = { containerBounds, keyboardHeight, contentViewDefaultFrame in
            v.qmui_frameApplyTransform = CGRectSetXY(v.frame, CGFloatGetCenter(containerBounds.width, v.frame.width), containerBounds.height - v.frame.height)
        }
        modalViewControllerForAddSubview.view.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
        modalViewControllerForAddSubview.animationStyle = .slide
        modalViewControllerForAddSubview.show(in: view, animated: true, completion: nil)
        
        v.pushBlock = { [unowned self] in
            self.modalViewControllerForAddSubview.hideWith(animated: true)
            self.navigationController?.qmui_pushViewController(FQExplainViewController(), animated: true)
        }
        v.closeBlock = { [unowned self] in
            self.modalViewControllerForAddSubview.hideWith(animated: true)
        }
    }
    
    @objc func toManual() {
        navigationController?.qmui_pushViewController(FQManualCerificationViewController(), animated: true)
    }

    override func setupNavigationItems() {
        super.setupNavigationItems()
        title = "身份认证"
    }
}
